#include"ServerSocket.h"
#include"SocketException.h"
#include<string>
#include<iostream>
#include<thread>
#include<vector>
#include<signal.h>
#include"c++_mysql/MyDB.h"
#include"vector_serialization.h"

using namespace std;

//构造sql语句
void makesql(string &data) {
	map<string,string> smap;
	load(data,smap);
	string sql;
	//vector<string>::iterator beg = svec.begin();
	//insert staff info
	string icode = "001";
	cout << "icode:" << icode << endl;
	cout << "code:" << smap["code"] << endl;
	if (!smap["code"].compare(icode)) {
		cout << "yes" << endl;
		sql = "insert into student values('";
	
		sql.insert(sql.size(), smap["name"]);
		sql.insert(sql.size(),"',");
		sql.insert(sql.size(), smap["age"]);
		sql.insert(sql.size(),",'");
		sql.insert(sql.size(), smap["sex"]);
		sql.insert(sql.size(), "')");
		cout << sql << endl;
	}
	data = sql;

}

//处理客户端的请求
void handle_client(ServerSocket *new_sock) {
	cout << "handle_client called" << endl;
	MyDB db;
	db.initDB("localhost","root","930504","bank");

	try {
		while(true) {
			string data;
			//接收数据存放到data
			*new_sock >> data;
			string outputdata;
			//构造sql语句
			makesql(data);
			db.execSQL(data,outputdata);
			cout << "client:" << data << endl;
			*new_sock << outputdata;
			if (data == "quit") {
				cout << "%%" << endl;
				break;
			}
		}
	}
	catch(SocketException &e) {}
}

int main ( int argc, char *argv[] )
{
	cout << "running....\n";
	try
    {
		// Create the socket
		ServerSocket server ( 30000 );

		while ( true )
		{
			ServerSocket *new_sock = new ServerSocket();
			//ServerVec.push_back(new_sock);
			server.accept ( *new_sock );
			thread *client_thread = new thread(handle_client,new_sock);
			//detach将线程对象和线程执行的事例分离，执行部分结束后释放分配的资源
			client_thread->detach();
			//ThreadVec.push_back(client_thread);
			delete client_thread;
			//cout << "thread id: " << client_thread->get_id() << endl;
		}
    }
	catch ( SocketException& e )
	{
		cout << "Exception was caught:" << e.description() << "\nExiting.\n";
    }
	cout << "yunxing" << endl;

	return 0;
}
